<?php

declare(strict_types=1);

namespace app\command;

use app\common\order\model\OrderCollect;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;

class Order extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('order')
            ->addOption('type', null, Option::VALUE_REQUIRED, 'the order notice')
            ->setDescription('the order command');
    }

    protected function execute(Input $input, Output $output)
    {
        // 指令输出
        $output->writeln('order');
        $type = $input->getOption('type');
        if (empty($type)) {
            $output->writeln('type is empty');
            return;
        }

        switch ($type) {
            case 'syncCollectComplete':
                $this->sync_collect_complete();
                break;
        }
    }

    protected function sync_collect_complete()
    {
        $collectModel = new \app\common\order\model\OrderCollect();
        // 获取所有未同步的收款单
        $where = [];
        $where[] = ['is_sync_complete', '=', 0];
        // 定金、尾款、全款
        $where[] = ['income_type_id', 'in', [1, 2, 3]];
        $incomeModel = new \app\common\order\model\OrderIncome();
        $incomes = $incomeModel->where($where)->select();
        foreach ($incomes as $income) {
            // 设置收状态的完成度
            $map = [];
            $map[] = ['order_id', '=', $income['order_id']];
            $map[] = ['type', '=', $income['income_type_id']];
            $collect = $collectModel->where($map)->find();
            if ($collect) {
                $complete = ($income['total'] + $collect['price']) / $collect['price'] * 100;
                $collect->save(['complete' => $complete]);
            }
            $income->save(['is_sync_complete' => 1]);
        }
    }
}
